package week4;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ProgramOfStudy implements Iterable<Course>, Serializable {

    private List<Course> list;

    // 构造一个最初空的学习项目
    public ProgramOfStudy()
    {
        list = new LinkedList<Course>();
    }

    // 添加course到列表的尾部
    public void addCourse(Course course)
    {
        if (course != null)
        {
            list.add(course);
        }
    }

    // 查询并且返回匹配prefix和number的course
    public Course find(String prefix, int number)
    {
        for (Course course : list)
        {
            if (prefix.equals(course.getPrefix()) && number == course.getNumber())
            {
                return course;
            }
        }
        return null;
    }

    // 在目标course后插入course，如果course为空或者目标course不存在则无操作
    public void addCourseAfter(Course target, Course newCourse)
    {
        if (target == null || newCourse == null) {
            return;
        }

        int targetIndex = list.indexOf(target);
        if (targetIndex != -1) {
            list.add(targetIndex + 1, newCourse);
        }
    }

    // 用新course替换目标course，如果course为空或者目标course不存在则无操作
    public void replace(Course target, Course newCourse)
    {
        if (target == null || newCourse == null) {
            return;
        }

        int targetIndex = list.indexOf(target);
        if (targetIndex != -1)
            list.set(targetIndex, newCourse);
    }

    // 创建并返回这个学习项目的字符串形式
    public String toString()
    {
        String result = "";
        for (Course course : list) {
            result += course + "\n";
        }
            return result;
    }

    // 返回这个学习项目的迭代器
    @Override
    public Iterator<Course> iterator()
    {
        return list.iterator();
    }

    // 将这个学习项目的序列化版本保存到文件
    public void save(String fileName) throws IOException
    {
        FileOutputStream fos = new FileOutputStream(fileName);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(this);
        oos.flush();
        oos.close();
    }

    // 读取学习项目的序列化版本从文件
    public static ProgramOfStudy load(String fileName) throws IOException, ClassNotFoundException
    {
        FileInputStream fis = new FileInputStream(fileName);
        ObjectInputStream ois = new ObjectInputStream(fis);
        ProgramOfStudy pos = (ProgramOfStudy) ois.readObject();
        ois.close();

        return pos;
    }
}
